const { cartList, deleteCart, decreaseCart, increaseCart } = require('../../api/cart')
const { API_OK } = require('../../utils/setting')
const app = getApp()

Page({
  data: {
    loading: true,
    cart: [],
    checkedAll: false,
    totalPrice: 0,
    totalCredit: 0
  },
  pageData: {
    startX: 0
  },
  onLoad: function () {},
  onShow() {
    wx.showLoading({ title: '拼命加载中' })
    if (wx.getStorageSync('token')) {
      this.getCart()
    } else {
      app.tokenReadyCallback = this.getCart
      app.getTokenFailedCallback = wx.hideLoading
    }
  },
  selectGoods(e) {
    const index = e.currentTarget.dataset.index
    this.data.cart[index].selected = !this.data.cart[index].selected
    this.setData({
      cart: this.data.cart,
      checkedAll: this.data.cart.every(item => item.selected)
    })
    this.calcTotal()
  },
  /**
   * 修改所有购物车商品的选则状态
   */
  changeAllStatus() {
    this.data.cart.forEach(item => { item.selected = !this.data.checkedAll })
    this.setData({
      cart: this.data.cart,
      checkedAll: !this.data.checkedAll
    })
    this.calcTotal()
  },
  /**
   * 计算总价格和总积分
   */
  calcTotal() {
    let price = 0
    this.data.cart.forEach(item => {
      if (!item.selected) return
      price += item.price * item.number
    })
    this.setData({
      totalPrice: price,
      totalCredit: this.data.totalPrice
    })
  },
  // swipe-cell 逻辑 ▽▽▽▽▽▽
  showDeleteButton(e) {
    const index = e.currentTarget.dataset.index
    this.setXmove(index, -65)
  },
  hideDeleteButton(e) {
    const index = e.currentTarget.dataset.index
    this.setXmove(index, 0)
  },
  setXmove(index, xmove) {
    const cart = JSON.parse(JSON.stringify(this.data.cart))
    cart[index].xmove = xmove
    this.setData({ cart })
  },
  handleTouchStart(e) {
    this.pageData.startX = e.touches[0].pageX
  },
  handleTouchEnd(e) {
    if (Math.abs(this.pageData.startX - e.changedTouches[0].pageX) < 1 || !this.pageData.startX) {
      this.pageData.startX = 0
      return
    }
    if (e.changedTouches[0].pageX < this.pageData.startX && e.changedTouches[0].pageX - this.pageData.startX <= -30) {
      this.showDeleteButton(e)
    } else if (e.changedTouches[0].pageX > this.pageData.startX && e.changedTouches[0].pageX - this.pageData.startX < 30) {
      this.showDeleteButton(e)
    } else {
      this.hideDeleteButton(e)
    }
    this.pageData.startX = 0
  },
  handleMovableChange(e) {
    if (e.detail.source === 'friction') {
      if (e.detail.x < -30) {
        this.showDeleteButton(e)
      } else {
        this.hideDeleteButton(e)
      }
    } else if (e.detail.source === 'out-of-bounds' && e.detail.x === 0) {
      this.hideDeleteButton(e)
    }
  },
  // swipe-cell 逻辑 △△△△△△
  /**
   * 减少购物车数量
   */
  async decrease(e) {
    const { index } = e.currentTarget.dataset
    if (this.data.cart[index].number <= 1) {
      wx.showToast({ title: '数量不能再减少了', icon: 'none', duration: 1500, mask: false })
      return
    }
    try {
      wx.showLoading({ title: '拼命加载中', mask: true })
      const res = await decreaseCart({
        data: {
          goods_id: this.data.cart[index].id,
          goods_sku_id: this.data.cart[index].skuId
        },
        header: { 'Content-Type':'application/x-www-form-urlencoded' },
        callback: wx.hideLoading
      })
      // console.log(res)
      if (res.code === API_OK) {
        this.data.cart[index].number -= 1
        this.setData({ cart: this.data.cart })
        this.data.cart[index].selected && this.calcTotal()
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 增加购物车数量
   */
  async increase(e) {
    const { index } = e.currentTarget.dataset
    if (this.data.cart[index].number >= this.data.cart[index].stock) {
      wx.showToast({ title: '数量不能再增加了', icon: 'none', duration: 1500, mask: false })
      return
    }
    try {
      wx.showLoading({ title: '拼命加载中', mask: true })
      const res = await increaseCart({
        header: { 'Content-Type':'application/x-www-form-urlencoded' },
        data: {
          goods_id: this.data.cart[index].id,
          goods_num: 1,
          goods_sku_id: this.data.cart[index].skuId
        },
        callback: wx.hideLoading
      })
      console.log(res)
      if (res.code === API_OK) {
        this.data.cart[index].number += 1
        this.setData({ cart: this.data.cart })
        this.data.cart[index].selected && this.calcTotal()
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 删除购物车
   */
  async deleteCart({ currentTarget }) {
    wx.showLoading({ title: '拼命加载中', mask: true })
    const { index } = currentTarget.dataset
    try {
      const res = await deleteCart({
        data: { cart_ids: `${this.data.cart[index].id}_${this.data.cart[index].skuId}` },
        callback: wx.hideLoading
      })
      console.log(res)
      if (res.code === API_OK) {
        this.data.cart.splice(index, 1)
        this.setData({ cart: this.data.cart })
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 获取购物车数据
   */
  async getCart() {
    try {
      const res = await cartList({ callback: wx.hideLoading })
      console.log(res)
      if (res.code === API_OK) {
        this.setData({
          loading: false,
          cart: res.data.goods_list.map(item => {
            let specificationStr = []
            let specificationIdArr = item.goods_sku_id.split('_')
            specificationIdArr.length > 1 && specificationIdArr.forEach(id => {
              specificationStr.push(item.spec_rel.filter(el => el.spec_value_id === id * 1)[0].spec_value)
            })
            let stock = item.sku.filter(el => el.spec_sku_id === item.goods_sku_id)[0].stock_num
            return {
              id: item.goods_id,
              image: item.image && item.image.length && item.image[0].file_path,
              name: item.goods_name,
              skuId: item.goods_sku_id,
              specifications: specificationStr.join(','),
              price: item.goods_price,
              number: item.total_num * 1,
              stock,
              selected: false,
              xmove:0
            }
          })
        })
      }
    } catch(err) {
      console.warn(err)
      this.setData({ loading: false })
    }
  },
  /**
   * 获取已选择的商品
   */
  getCartIds() {
    return this.data.cart.reduce((ids, item) => {
      item.selected && ids.push(`${item.id}_${item.skuId}`)
      return ids
    }, [])
  },
  /**
   * 提交订单
   */
  submit() {
    const cartIds = this.getCartIds()
    if (!cartIds) {
      wx.showToast({ title: '请选择商品', icon: 'none', duration: 1500, mask: false })
      return
    }
    wx.navigateTo({
      url: `/pages/confirm-order/confirm-order?order_type=cart&cart_ids=${cartIds}`
    })
  },
  goStore() {
    wx.switchTab({
      url: '/pages/store/store'
    })
  }
})
